#ifndef MJPEGWORKER_H
#define MJPEGWORKER_H

#include <QObject>
#include "mjpg.h"
#include "ui_mjpg.h"
#include <QThread>
#include <QImageReader>
#include <QBuffer>
#include <QDateTime>
class MJPEGWorker : public QObject
{
    Q_OBJECT
public:
    explicit MJPEGWorker(QObject *parent = 0);
    MJPEGWorker(QNetworkReply* reply, QLabel* imageLabel)
            : m_reply(reply), m_imageLabel(imageLabel) {
            connect(m_reply, &QNetworkReply::readyRead, this, &MJPEGWorker::processFrame);
            connect(m_reply, &QNetworkReply::finished, this, &MJPEGWorker::onFinished);
        }
    ~MJPEGWorker();

signals:
    void updateImage(const QPixmap& pixmap);  // 更新UI信号
        void finished();  // 请求完成信号

public slots:
    void processFrame() {
            m_buffer.append(m_reply->readAll());

            int startIdx = m_buffer.indexOf("\xFF\xD8"); // JPEG SOI marker
            int endIdx = m_buffer.indexOf("\xFF\xD9", startIdx); // JPEG EOI marker

            if (startIdx != -1 && endIdx != -1 && endIdx > startIdx) {
                QByteArray jpegData = m_buffer.mid(startIdx, endIdx - startIdx + 2);
                m_buffer.remove(0, endIdx + 2);  // Remove the processed frame

                // 使用QBuffer提高解码效率
                QBuffer buffer(&jpegData);
                buffer.open(QIODevice::ReadOnly);

                QImageReader reader(&buffer, "JPEG");
                if (reader.canRead()) {
                    QImage image = reader.read();
                    if (!image.isNull()) {
                        QPixmap pixmap = QPixmap::fromImage(image).scaled(m_imageLabel->size(), Qt::KeepAspectRatio);
                        emit updateImage(pixmap);  // 通知UI更新图片
                    }
                }
            }
        }

        void onFinished() {
            m_reply->deleteLater();
            emit finished();  // 发出完成信号
        }
private:
        QNetworkReply* m_reply;
           QLabel* m_imageLabel;
           QByteArray m_buffer;
};

#endif // MJPEGWORKER_H
